﻿using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Mbl.ParameterizedTest
{
    public class TestResultAggregator
    {
        private readonly List<TestCaseAssertionResult> _assertionResults = new List<TestCaseAssertionResult>();

        public void AddResult(TestCaseAssertionResult assertionResult)
        {
            _assertionResults.Add(assertionResult);
        }

        public void AddRange(IEnumerable<TestCaseAssertionResult> testResults)
        {
            _assertionResults.AddRange(testResults);
        }

        public void FailIfAnyErrors()
        {
            if (_assertionResults.Any(result => !result.Holds))
            {
                var errorMessage = BuildErrorMessage();
                TestResultSignal.Failed(errorMessage);
            }
        }

        private string BuildErrorMessage()
        {
            var errorBuilder = new StringBuilder();
            var failedTests = _assertionResults.Count(r => !r.Holds);

            errorBuilder.AppendLine($"{failedTests} of {_assertionResults.Count} tests failed:");            

            int testNr = 0;
            foreach (var assertionResult in _assertionResults)
            {
                testNr++;
                if (assertionResult.Holds)
                {
                    continue;
                }
                                
                var testNrDisplay = testNr.ToFixedNr(_assertionResults.Count);

                var errorMessage = assertionResult.ErrorMessage.EndsWith(".")
                    ? assertionResult.ErrorMessage
                    : assertionResult.ErrorMessage + ".";

                errorBuilder.AppendLine($"  Test {testNrDisplay}: {errorMessage} {assertionResult.Justification}");
            }

            return errorBuilder.ToString();
        }        
    }
}